<template>
  <el-form ref="form" :model="user" :rules="rules" label-width="auto">
    <el-form-item :label="$t('message.touxian')" prop="faceImg2">
      <transition name="fade">
        <Cropper
          v-if="dialogCropperVisible"
          :option-img="optionImg"
          :fileinfo="fileinfo"
          use-type="USER_IMG"
          :fixed-number="[32, 32]"
          @formSubmit="cropperSubmit"
          @formClose="cropperClose"
        />
      </transition>
      <el-upload
        class="device-uploader"
        :action="uploadFileUrl"
        :data="uploadData"
        :show-file-list="false"
        accept=".jpg,.png"
        :on-change="addFileChange"
        :auto-upload="false"
      >
        <i class="el-icon-plus uploader-icon" />
        <div
          v-show="user.faceImg2"
          class="file"
          :style="'background-image: url(' + user.faceImg2 + ')'"
        >
          <div class="delete">
            <i class="el-icon-delete icon" @click.stop="deleteYyzzImage" />
          </div>
        </div>
      </el-upload>
    </el-form-item>
    <el-form-item :label="$t('message.yhnc')" prop="nickName">
      <el-input v-model="user.nickName" />
    </el-form-item>
    <el-form-item :label="$t('message.zsxm')">
      <el-input v-model="user.realName" />
    </el-form-item>
    <el-form-item :label="$t('message.sfzh')">
      <el-input v-model="user.identityNumber" maxlength="18" />
    </el-form-item>
    <el-form-item :label="$t('message.glxpj')">
      <el-select v-model="user.printerId" :placeholder="$t('message.qxz')" clearable>
        <el-option
          v-for="item in list"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-button v-preventReClick :loading="subLoading" type="primary" size="mini" @click="submit">{{ $t('message.baocun') }}</el-button>
      <el-button v-preventReClick type="danger" size="mini" @click="close">{{ $t('message.gb') }}</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { uploadFile, updateMyUser, printerList } from '@/api'
import Cropper from '@/components/cropper'
export default {
  components: {
    Cropper
  },
  props: {
    // eslint-disable-next-line vue/require-default-prop
    user: { type: Object }
  },
  data() {
    return {
      subLoading: false,
      dialogCropperVisible: false,
      optionImg: '',
      files: {},
      fileinfo: {},
      uploadFileUrl: uploadFile,
      list: [],
      uploadData: {
        folder: 'USER_IMG',
        type: ''
      },
      // 表单校验
      rules: {
        faceImg2: [
          { required: true, message: this.$t('message.yhtxbnwk'), trigger: 'blur' }
        ],
        nickName: [
          { required: true, message: this.$t('message.yhncbnwk'), trigger: 'blur' }
        ],
        realName: [
          { required: true, message: this.$t('message.zsxmbnwk'), trigger: 'blur' }
        ],
        identityNumber: [
          { required: true, message: this.$t('message.sfzhbnwk'), trigger: 'blur' },
          {
            required: true,
            pattern:
              /^(([1-9][0-9]{5}(19|20)[0-9]{2}((0[1-9])|(1[0-2]))([0-2][1-9]|10|20|30|31)[0-9]{3}([0-9]|X|x))|([1-9][0-9]{5}[0-9]{2}((0[1-9])|(1[0-2]))([0-2][1-9]|10|20|30|31)[0-9]{3}))$/,
            message: this.$t('message.qsrzqdsfzh'),
            trigger: 'blur'
          }
        ],
        email: [
          { required: true, message: this.$t('message.yxdzbnwk'), trigger: 'blur' },
          {
            type: 'email',
            message: this.$t('message.qsrzrdyxdz'),
            trigger: ['blur', 'change']
          }
        ],
        phone: [
          { required: true, message: this.$t('message.sjhmbnwk'), trigger: 'blur' },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: this.$t('message.qsrzqdsjhm'),
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    this.getPrinter()
  },
  methods: {
    getPrinter() {
      printerList({
        param: {
          venueId: sessionStorage.getItem('venueId')
        },
        gymId: sessionStorage.getItem('venueId')
      }, sessionStorage.getItem('venueId')).then(res => {
        if (res.errorCode === '000000') {
          this.list = res.recordList
        }
      }).catch(err => {
        console.log('-----', err)
      })
    },
    // 上传头像成功
    uploadSuccess(res, file, fileList) {
      if (res.success) {
        this.$set(this.user, 'faceImg2', res.showUrl)
        this.$set(this.user, 'faceImg', res.insertUrl)
      } else {
        this.$message.error(res.msg || this.$t('message.scsb'))
      }
    },
    // 上传图片，开始裁剪
    async addFileChange(file) {
      // 上传，拿到file文件
      this.files = file.raw
      this.$nextTick(() => {
        this.optionImg = URL.createObjectURL(file.raw)
        this.fileinfo = file.raw
        this.dialogCropperVisible = true
      })
    },
    // 裁剪确定按钮
    cropperSubmit(config) {
      // preImg 完整路径  urlPre 不包含域名
      if (config.success) {
        this.$set(this.user, 'faceImg2', config.showUrl)
        this.$set(this.user, 'faceImg', config.insertUrl)
        this.dialogCropperVisible = false
      } else {
        this.$message.error(config.msg || this.$t('message.scsb'))
        this.dialogCropperVisible = false
      }
    },
    // 裁剪取消
    cropperClose() {
      this.dialogCropperVisible = false
    },
    // 删除头像
    deleteYyzzImage() {
      this.$set(this.user, 'faceImg2', '')
      this.$set(this.user, 'faceImg', '')
    },
    submit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const param = { ...this.user }
          param.roleList = []
          param.userId = sessionStorage.getItem('userId')
          this.subLoading = true
          updateMyUser({
            param
          })
            .then((res) => {
              this.subLoading = false
              if (res.errorCode === '000000') {
                this.$message.success(this.$t('message.xgcg'))
                this.$emit('loadData', this.user)
              }
            })
            .catch((err) => {
              this.subLoading = false
              console.log(err)
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    close() {
      this.$store.dispatch('tagsView/delView', this.$route)
      this.$router.push({ path: '/' })
    }
  }
}
</script>
<style lang="scss" scoped>
@import "@/styles/variables.scss";
.device-uploader {
  width: 80px;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  cursor: pointer;
  border: 1px dashed #ccc;
  border-radius: 8px;
  transition: all 0.3s;
  margin-right: 20px;
  &:hover {
    border-color: $menuActive;
    .uploader-icon {
      color: $menuActive;
    }
  }
  ::v-deep .el-upload {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    .file {
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
      background-size: contain;
      background-position: center;
      background-repeat: no-repeat;
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      .delete {
        background-color: rgba(0, 0, 0, 0.5);
        position: absolute;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        display: none;
        align-items: center;
        justify-content: center;
        .icon {
          color: #fff;
        }
      }
      &:hover {
        .delete {
          display: flex;
        }
      }
    }
  }
  .uploader-icon {
    color: #aaaaaa;
    font-size: 22px;
    transition: all 0.3s;
  }
}
.line-style {
  margin-bottom: 20px;
}
.device-uploaders {
  ::v-deep .el-upload-list__item {
    width: 80px;
    height: 80px;
  }
  ::v-deep .el-upload {
    width: 80px;
    height: 80px;
    line-height: 80px;
  }
}
</style>
